package com.lei.springbootpractice.controller;

import com.lei.springbootpractice.pojo.CategoryPojo;
import com.lei.springbootpractice.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/categories")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping
    public List<CategoryPojo> getAllCategories() {
        return categoryService.getAllCategories();
    }

    @GetMapping("/{parentId}/subcategories")
    public List<CategoryPojo> getSubcategories(@PathVariable String parentId) {
        return categoryService.getSubcategories(parentId);
    }

    @GetMapping("/parents")
    public List<CategoryPojo> getParentCategories() {
        return categoryService.getParentCategories();
    }

    /**
     * 动态加载子分类的AJAX接口
     * 用于解决前端父分类选择后无法显示子分类的问题
     */
    @GetMapping("/ajax/{parentId}/subcategories")
    public List<CategoryPojo> getSubcategoriesAjax(@PathVariable String parentId) {
        System.out.println("AJAX请求获取子分类，父分类ID：" + parentId);
        List<CategoryPojo> subcategories = categoryService.getSubcategories(parentId);
        System.out.println("找到子分类数量：" + subcategories.size());
        return subcategories;
    }

    /**
     * 刷新所有分类数据的接口
     */
    @GetMapping("/refresh")
    public List<CategoryPojo> refreshAllCategories() {
        return categoryService.getAllCategories();
    }

    @GetMapping("/{categoryId}")
    public CategoryPojo getCategory(@PathVariable String categoryId) {
        return categoryService.getCategoryById(categoryId);
    }

    @PostMapping
    public boolean addCategory(@RequestBody CategoryPojo category) {
        return categoryService.addCategory(category);
    }

    @PutMapping
    public boolean updateCategory(@RequestBody CategoryPojo category) {
        return categoryService.updateCategory(category);
    }

    @DeleteMapping("/{categoryId}")
    public boolean deleteCategory(@PathVariable String categoryId) {
        return categoryService.deleteCategory(categoryId);
    }
}